/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eng.scc.core.parts;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.JTextField;

/**
 *
 * @author Rafael
 */
public class DecimalTextField extends JTextField
{
    DecimalFormat decimalFormat = new DecimalFormat();
    
    NumberFormat valueFormat = NumberFormat.getInstance();
    {
        valueFormat.setMinimumFractionDigits( 2 );
        valueFormat.setMaximumFractionDigits( 2 );
    }
    
    public DecimalTextField()
    {
        setText( "0,00" );
        setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        addFocusListener( new FocusAdapter() 
        {

            @Override
            public void focusGained( FocusEvent e )
            {
                setSelectionStart( 0 );
                setSelectionEnd( getText().length() );
                setHorizontalAlignment(javax.swing.JTextField.LEFT);
            }
            
            @Override
            public void focusLost( FocusEvent e )
            {
                try
                {
                    setText( valueFormat.format( decimalFormat.parse( getText() ).doubleValue() ) );
                }
                
                catch ( Exception ex )
                {
                    setText( "0,00" );
                }
                
                finally
                {
                    setHorizontalAlignment(javax.swing.JTextField.RIGHT);
                }
            }
        });
    }
    
    public double getValue()
    {
        try
        {
            return decimalFormat.parse( getText() ).doubleValue();   
        }
        catch ( Exception e )
        {
        }
        
        return 0;
    }
    
    public void setValue( double d )
    {
        setText( valueFormat.format( d ) );
    }
}
